#import "SecurityUtility.h"

@implementation SecurityUtility
+ (NSString*)randomStringWithLength:(int)length
{
    NSString * source = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
    NSMutableString * resultStr = [NSMutableString stringWithCapacity:length];
    for (int i=0; i<length; i++) {
        int index = [SecurityUtility getRandomNumber:0 to:(int)source.length-1];
        NSString * theChar = [source substringWithRange:NSMakeRange(index,1)];
        [resultStr appendString:theChar];
    }
    return resultStr;
}

+(int)getRandomNumber:(int) from to:(int)to{
    return (int)(from + (arc4random() % (to -from + 1)));
}

+(NSString *)hexStringWithData:(NSData *)data {
    const unsigned char *dataBuffer = (const unsigned char *)[data bytes];
    if (!dataBuffer) {
        return [NSString string];
    }
    
    NSUInteger          dataLength  = [data length];
    NSMutableString     *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
    
    for (int i = 0; i < dataLength; ++i) {
        [hexString appendFormat:@"%02x", (unsigned char)dataBuffer[i]];
    }
    return [NSString stringWithString:hexString];
}

+ (NSData *)dataWithHexString:(NSString *)hexString {
    const char *chars = [hexString UTF8String];
    int i = 0;
    NSUInteger len = hexString.length;
    
    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;
    
    while (i < len) {
        byteChars[0] = chars[i++];
        byteChars[1] = chars[i++];
        wholeByte = strtoul(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }
    
    return data;
}


@end
